import type { ObjectDirective, DirectiveBinding } from 'vue'
import { storeToRefs } from 'pinia'
import { useUsersStore } from '@/stores'
import { isArray } from '@/utils'

const bindPermission: ObjectDirective = {
  mounted (
    el: HTMLDivElement,
    binding: DirectiveBinding<string | Array<string>>
  ) {
    const { permissionCodes } = storeToRefs(useUsersStore())
    const value = binding.value
    if (typeof value === 'string') {
      if (!permissionCodes.value.find((o) => o === value)) {
        el.parentNode && el.parentNode.removeChild(el)
      }
    } else if (isArray(value)) {
      if (!permissionCodes.value.some((o) => value.includes(o))) {
        el.parentNode && el.parentNode.removeChild(el)
      }
    } else {
      console.warn('v-permission need to pass in a string or an array string')
    }
  }
}

const hasPermission = (value: string | Array<string>) => {
  const { permissionCodes } = storeToRefs(useUsersStore())
  if (typeof value === 'string') {
    if (!permissionCodes.value.find((o) => o === value)) {
      return false
    }
  } else if (isArray(value)) {
    if (!permissionCodes.value.some((o) => value.includes(o))) {
      return false
    }
  }
  return true
}

export { bindPermission, hasPermission }
